package com.ruoyi.web.controller.warning;

import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.ruoyi.common.annotation.Anonymous;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.warning.domain.entity.EventDetail;
import com.ruoyi.warning.service.IEventDetailService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.io.IOUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.nio.charset.StandardCharsets;

/**
 * <p>
 * 告警事件的详情表 前端控制器
 * </p>
 *
 * @author chenhc
 * @since 2025-05-20
 */
@RestController
@RequestMapping("/eventDetail")
@Api(tags = "事件详情", description = "用于处理事件详情相关操作的控制器")
public class EventDetailController {
    @Resource
    private IEventDetailService iEventDetailService;
    @ApiOperation("接收事件")
    //@PreAuthorize("@ss.hasPermi('system:config:export')")
    @Anonymous
    @PostMapping(value = "/receiveEvent")
    public R receiveEvent(HttpServletRequest request) throws Exception {
        System.out.println("========================");
        String json = IOUtils.toString(request.getInputStream(), StandardCharsets.UTF_8);
        System.out.println(json);
        System.out.println("========================");
        json = cleanIllegalEscapes(json);
        Object obj = JSONObject.parse(json);
        iEventDetailService.receiveEvent(obj);
        return R.ok();
    }

    /**
     * 清理非法的转义字符
     * @param json 原始JSON字符串
     * @return 清理后的JSON字符串
     */
    private String cleanIllegalEscapes(String json) {
        if (json == null || json.isEmpty()) {
            return json;
        }

        // 将非法的反斜杠转义为正确的双反斜杠
        // 匹配不是标准JSON转义字符的反斜杠序列
        return json.replaceAll("\\\\([^\"\\\\/bfnrtu])", "\\\\\\\\$1");
    }

    @ApiOperation("查看事件详情")
    //@PreAuthorize("@ss.hasPermi('system:config:export')")
    @GetMapping(value = "/getEventDetail/{id}")
    public R getEventDetail(@PathVariable String id) throws Exception {
        return R.ok(
                iEventDetailService.list(
                        new LambdaQueryWrapper<EventDetail>()
                                .eq(EventDetail::getEventId,id)
                                .orderByDesc(EventDetail::getCreateTime)));
    }
}
